package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.project.bean.RoleBean;
import com.project.bean.UserBean;
import com.project.mapper.IRoleMapper;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserMapper userMapper;
    @Autowired
    private IRoleMapper roleMapper;


    @Override
    public UserBean login(String userName, String userPwd) {
      UserBean user= userMapper.login(userName, userPwd);
      if (user == null){
          return null;
      }
      List<RoleBean>roleList = roleMapper.findRoleGradeByUserId(user.getId());
      user.setRoleList(roleList);
      return user;
    }

    @Override
    public PageInfo<UserBean> findByItem(int page, int pageSize, String name) {
        PageHelper.startPage(page,pageSize);
        PageInfo<UserBean>pageInfo=PageInfo.of(userMapper.findByItem(name));
        return pageInfo;
    }

    @Override
    public UserBean findById(int id) {
        return userMapper.findById(id);
    }

    @Override
    public boolean addUser(UserBean user, int[] roleArray) {
        userMapper.addUser(user);
        roleMapper.addRoleByUserId(user.getId(), roleArray);
        return true;
    }

    @Override
    public void delUser(int id) {
        userMapper.delUser(id);
        roleMapper.delUserRoleByUserId(id);
    }

    @Override
    public void updateUser(int id, int[] roleArray) {

    }

    @Override
    public String updatePwd(int id, String oldPwd, String newPwd, String newPwd2) {
       UserBean user = userMapper.findById(id);
       if (!user.getUserPwd().equals(oldPwd)){
           return "oldPwd";
       }
       if (!newPwd.equals(newPwd2)){
           return "newPwdError";
       }
       user.setUserPwd(newPwd);
       userMapper.updatePwd(id,oldPwd,newPwd,newPwd2);
            return "updatePwd";

    }
}
